﻿using Microsoft.Extensions.Options;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using NetMicro.Core.Exceptions;
using NetMicro.Core.Ioc.Attributes;

namespace NetMicro.MongoProvider
{
    /// <summary>
    /// 
    /// </summary>
    public abstract class MongoDBContext
    {

        /// <summary>
        /// MongoDB连接信息
        /// </summary>
        public MongoDBConnectionConfig host { get; }

        /// <summary>
        /// 获取分库链接
        /// </summary>
        public ISubDatabaseMongoConfig SubDatabaseMongoConfig { get; }



        /// <summary>
        /// 
        /// </summary>
        /// <param name="mongoDBHost"></param>
        /// <param name="mongoConfig"></param>
        public MongoDBContext(MongoDBConnectionConfig mongoDBHost, ISubDatabaseMongoConfig mongoConfig)
        {
            if (mongoDBHost != null)
            {
                host = mongoDBHost;
            }
            SubDatabaseMongoConfig = mongoConfig;
        }
        /// <summary>
        /// 客户端
        /// </summary>
        public MongoClient Client()
        {
            MongoDBConnectionConfig mongoDBConnectionConfig = SubDatabaseMongoConfig.GetConnectionConfig();
            if (mongoDBConnectionConfig != null)
            {
                return new MongoClient(mongoDBConnectionConfig.ConnectionString);
            }

            if (host == null)
            {
                throw new MongoProviderException("MongoDBClient.host不能为空");
            }
            if (string.IsNullOrWhiteSpace(host.ConnectionString))
            {
                throw new MongoProviderException("MongoDBClient.host.ConnectionString,MongoDB连接字符串未赋值");
            }

            return new MongoClient(host.ConnectionString);
        }
        /// <summary>
        /// 获取集合实例
        /// </summary>
        /// <returns></returns>
        public IMongoCollection<T> GetCollectionInstance<T>(string collection)
        {
            var dataBase = GetMongoDatabase();
            return dataBase.GetCollection<T>(collection);
        }

        /// <summary>
        /// 获取集合实例
        /// </summary>
        /// <returns></returns>
        public IMongoDatabase GetMongoDatabase()
        {
            var dataBaseName = host.DataBase;
            if (string.IsNullOrWhiteSpace(dataBaseName))
            {
                var mongoUrl = new MongoUrlBuilder(host.ConnectionString);
                dataBaseName = mongoUrl.DatabaseName;
            }
            IMongoDatabase dataBase = Client().GetDatabase(dataBaseName);
            return dataBase;
        }

    }
}
